import { Properties } from 'csstype'
import { tryOnDocumentLoaded } from 'shared/utils/utils'

export class DouyinExtensionTool extends HTMLElement {
  private sheet?: CSSStyleSheet

  constructor(html: string, listenerMap: Record<string, () => void>) {
    super()

    const shadowRoot = this.attachShadow({ mode: 'open' })
    shadowRoot.innerHTML = html

    const icons = shadowRoot.querySelectorAll('[data-type]') as any as HTMLElement[]
    Array.from(icons).forEach((icon) => {
      const listener = listenerMap[icon.dataset.type as string]
      if (typeof listener === 'function') {
        icon.addEventListener('click', listener)
      }
    })

    tryOnDocumentLoaded(() => {
      document.body.append(this)
    })
  }

  updateHostStyle(style: Properties) {
    if (!this.sheet) {
      this.shadowRoot!.adoptedStyleSheets = [(this.sheet = new CSSStyleSheet())]
    }
    const csstext = Object.entries(style)
      .map(([k, v]) => `${k}:${v};`)
      .join('')
    this.sheet.replace(`:host {${csstext}}`)
  }
}

customElements.define('douyin-extension-tool', DouyinExtensionTool)
